<?php
declare(strict_types=1);
namespace Haozing\FastCore\Middleware;

use Hyperf\Context\Context;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CorsMiddleware implements MiddlewareInterface
{
    #[Inject]
    protected ConfigInterface $config;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 从配置文件中获取租户标识
        $response_origin = $this->config->get('fastCore.response_origin', '*');
        $response_credentials = $this->config->get('fastCore.response__credentials', 'true');
        $response_headers = $this->config->get('fastCore.response_headers', 'DNT,Keep-Alive,User-Agent,Cache-Control,Content-Type,Authorization,Tid');

        $response = Context::get(ResponseInterface::class);
        $response = $response->withHeader('Access-Control-Allow-Origin', $response_origin)
            ->withHeader('Access-Control-Allow-Credentials', $response_credentials)
            // Headers 可以根据实际情况进行改写。
            ->withHeader('Access-Control-Allow-Headers', $response_headers);

        Context::set(ResponseInterface::class, $response);

        if ($request->getMethod() == 'OPTIONS') {
            return $response;
        }

        return $handler->handle($request);
    }
}